<?php

namespace app\admin\controller\shop;

use app\admin\model\City;
use app\admin\model\User;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;
    protected $searchFields = 'shop.name,shop.mobile';
    protected $noNeedRight = ['selectpage','getUser'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shop;
        $this->view->assign("shopType", $this->model->getShopType());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("joinBalance", $this->model->isJoinBalance());

    }

    protected function import()
    {
        return parent::import();
    }

//    public function selectpage()
//    {
//        return parent::selectpage(); // TODO: Change the autogenerated stub
//    }

    public function ajaxList()
    {

        $list = Db::name('shop')->field('id as value,name')->select();

        $this->success('', '', $list);

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user','supervision'])
                ->where($where)
                ->where('is_fake', -1)//排除虚拟店铺
                ->order($sort, $order)
                ->paginate($limit);

//            foreach ($list as $k => $v) {
//                $list[$k]['today'] = 0;
//                $list[$k]['all'] = 0;
//                $ratio = $v['ratio'];
//                $list[$k]['ratio'] = $ratio . "%";
//                if($v['is_join_balance'] == 1){
//                    $list[$k]['is_join_balance'] = "是";
//                }else{
//                    $list[$k]['is_join_balance'] = "否";
//                }
//            }

            foreach ($list as $k => $v) {
                $ref_mobile = '';
                $ref_name = '';
                $agent_id = $v['agent_id'];
                $agent_ratio = $v['agent_ratio'];
                $list[$k]['agent_ratio'] = $agent_ratio . "%";
                if ($agent_id !== null && $agent_id > 0) {
                    //查询对应代理商手机号和用户昵称
                    $result = Db::name('user')->where('id', $agent_id)->find();
                    $ref_mobile = $result['mobile'];
                    $ref_name = $result['username'];
                }

                $list[$k]['ref_mobile'] = $ref_mobile;
                $list[$k]['ref_name'] = $ref_name;

                $ratio = $v['ratio'];
                $list[$k]['ratio'] = $ratio . "%";
                if ($v['is_join_balance'] == 1) {
                    $list[$k]['is_join_balance'] = "是";
                } else {
                    $list[$k]['is_join_balance'] = "否";
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function getUser()
    {
        $mobile = $this->request->param('mobile');
        $userModel = new User();
        $userInfo = $userModel->where('mobile', $mobile)->where('org_id', 27)->find();
        if (empty($userInfo)) {
            $this->error('暂无用户');
        }
        $this->success('查询成功', '', $userInfo['id']);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        //是否采用模型验证
        if ($this->modelValidate) {
            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
            $this->model->validateFailException()->validate($validate);
        }

        $mobile = $params['mobile'];
        $ref_mobile = $params['ref_mobile'];
        $name = $params['name'];
        $city = $params['city'];
        $tel = $params['tel'];
        $shop_type = $params['shop_type'];
        if (empty($shop_type)) $this->error('店铺类型不能为空');
        if (empty($city)) {
            $this->error('城市参数不能为空');
        }
        try {
            $address = explode('/', $city);
            $province = $address[0];
            $city = $address[1];
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }

        // 判断城市是否存在，不存在添加
        $cityModel = new City();
        if(!empty($city)){
            $cityList = $cityModel->where('name', $city)->find();
            if (empty($cityList)) {
                $insertVal = [
                    'name' => $city,
                    'province_name' => $province,
                    'org_id' => 27
                ];
                $cityModel->insert($insertVal);
            }
        }

        $userModel = new User();
        $user = $userModel->where('mobile', $mobile)->find();
        $agenet_id = -1;
        if ($ref_mobile != "") {
            $refuser = $userModel->where('mobile', $ref_mobile)->find();
            if ($refuser != null) {
                $agenet_id = $refuser['id'];
            } else {
                $this->error("代理商数据不存在");
            }
        }
        if (!$user) {
            $dbUser = array();
            $dbUser['mobile'] = $mobile;
            $dbUser['group_id'] = 1;
            $dbUser['username'] = $mobile;
            $dbUser['status'] = 'normal';
            $dbUser['createtime'] = time();
            $user_id = $userModel->insertGetId($dbUser);

        } else {
            $user_id = $user['id'];
        }

        $db = array();
        $shopType = '';
        foreach ($shop_type as $m) {
            if($m == '台球'){
                $db['is_table'] = 1;
                $shopType = '台球';
            }

            if($m == '棋牌'){
                $db['is_qp'] = 1;
                $shopType = '棋牌';
            }

            if ($m == 'KTV') {
                $db['is_ktv'] = 1;
                $shopType = 'KTV';
            }
        }

        $db['mobile'] = $mobile;
        $db['name'] = $name;
        $db['city'] = $city;
        // 默认展示
        $db['logo'] = '/uploads/20240625/7af1cfa65074e07b6d646ada5bf83c12.png';
        $db['cover'] = '/uploads/20240408/b6455c0324056f44c2f0bb18c7384aea.jpg';

        $db['user_id'] = $user_id;
        $db['tel'] = $tel;
        $db['status'] = 3;
        $db['agent_id'] = $agenet_id;
        $db['ratio'] = $params['ratio'];

        $db['address'] = $params['address'];
        $db['lat'] = $params['lat'];
        $db['lng'] = $params['lng'];

        $db['agent_ratio'] = $params['agent_ratio'];
        $db['org_id'] = 27;
        $db['shop_type'] = $shopType;

        $id = $this->model->insertGetId($db);
        if ($id) {
            $this->success("成功");
        } else {
            $this->error("保存失败");
        }
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                $db = array();

                $mobile = $params['mobile'];
                $ref_mobile = $params['ref_mobile'];
                $name = $params['name'];
                $logo = $params['logo'];
                $city = $params['city'];
                $is_join_balance = $params['is_join_balance'];
                $qun_url = $params['qun_url'];
                $shopType = '';
                foreach ($params['shop_type'] as $m) {
                    if($m == '台球'){
                        $db['is_table'] = 1;
                        $shopType = '台球';
                    }

                    if($m == '棋牌'){
                        $db['is_qp'] = 1;
                        $shopType = '棋牌';
                    }

                    if ($m == 'KTV') {
                        $db['is_ktv'] = 1;
                        $shopType = 'KTV';
                    }
                }

                if ($city != "") {
                    try {
                        $address = explode('/', $city);
                        $province = $address[0];
                        $city = $address[1];
                    } catch (ValidateException|PDOException|Exception $e) {
                        $this->error('请按照 省份/城市 的格式，修改所在城市');
                    }
                    // 判断城市是否存在，不存在添加
                    $cityModel = new City();
                    $cityList = $cityModel->where('name', $city)->find();
                    if (empty($cityList)) {
                        $insertVal = [
                            'name' => $city,
                            'province_name' => $province,
                            'org_id' => 27
                        ];
                        $cityModel->insert($insertVal);
                    }

                    $db['city'] = $city;

                }

                $userModel = new User();
                $user = $userModel->where('mobile', $mobile)->find();
                $agenet_id = -1;
                if ($ref_mobile != "") {
                    $refuser = $userModel->where('mobile', $ref_mobile)->find();
                    if ($refuser != null) {
                        $agenet_id = $refuser['id'];
                    } else {
                        $this->error("代理商数据不存在");
                    }
                }
                if (!$user) {
                    $dbUser = array();
                    $dbUser['mobile'] = $mobile;
                    $dbUser['group_id'] = 1;
                    $dbUser['username'] = $mobile;
                    $dbUser['status'] = 'normal';
                    $dbUser['createtime'] = time();
                    $user_id = $userModel->insertGetId($dbUser);

                } else {
                    $user_id = $user['id'];
                }

                $db['open_time'] = $params['open_time'];
                $db['mobile'] = $mobile;
                $db['name'] = $name;
                $db['logo'] = $logo;
                $db['status'] = $params['status'];;
                $db['user_id'] = $user_id;
                $db['agent_id'] = $agenet_id;
                $db['ratio'] = $params['ratio'];
                $db['agent_ratio'] = $params['agent_ratio'];
                $db['dou_id'] = $params['dou_id'];
                $db['poi_id'] = $params['poi_id'];
                $db['mt_name'] = $params['mt_name'];
                $db['org_id'] = 27;
                $db['qun_url'] = $qun_url;
                $db['shop_type'] = $shopType;
                $db['is_join_balance'] = $is_join_balance;

                $id = $this->model->where('id', $params['id'])->update($db);
                if ($id) {
                    $this->success("编辑成功");
                } else {
                    $this->error("店铺内容无更新");
                }

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $ref_uid = $row['agent_id'];
        $row['ref_mobile'] = '';
        if ($ref_uid !== null && $ref_uid > 0) {
            //查询对应代理商手机号和用户昵称
            $result = Db::name('user')->where('id', $ref_uid)->find();
            $row['ref_mobile'] = $result['mobile'];
        }

        $shopType = array();
        if($row['is_table'] = 1){
            $shopType[] = '台球';
        }

        if($row['is_qp'] = 1){
            $shopType[] = '棋牌';
        }

        if ($row['is_ktv'] = 1) {
            $shopType[] = 'KTV';
        }

        $row['shop_type'] = $shopType;

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->where('is_fake', -1)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->where('is_fake', -1)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => $item[$primarykey] ?? '',
                        $field => $item[$field] ?? '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
